/*****************************************************************************
*	Copyrights(C) 2003 Acer Laboratries Inc. All Rights Reserved.
*
*	FILE NAME:		root.c
*
*	DESCRIPTION:	 This file contains application's root function - AppInit().
*				 It inits all modules used in the application and creates all the tasks
*				used. It also send a command to play the current tv program.
*
*
*	HISTORY:
*		Date 		Author 		Version 	Notes
*		=========	=========	=========	=========
*		2003-04-19	Xianyu Nie	Ver 0.1		Create File
*		..............	......	.		....			.....
*		2004-11-11 	Xionghua		Ver 0.2		modify for m3327
*****************************************************************************/
#include "head_file.h"
#include "./platform/board.h"
#include "./platform/board_cfg/board_cfg.h"

#include "win_com.h"
#include "copper_common/com_api.h"

#include <bus/rtc/rtc.h>

#ifdef SUPPORT_CAS_A
#include <api/libcas/abel/abel_mcas.h>
#include <api/libcas/abel/NN.h>
#endif

#include <api/libdbc/lib_dbc.h>
#include <boot/boot_chip.h>

#ifdef SUPPORT_CAS9
#include <api/librsa/rsa_verify.h>
#endif

extern enum Output_Frame_Ret_Code VDec_Output_Frame(struct Display_Info *pDisplay_info);
extern BOOL VDec_Release_FrBuf(UINT8 top_index, UINT8 bottom_index);
#ifdef AUTO_OTA
BOOL ota_power_flag;
#endif
//for nim_m3101_init.c  so bad!!! just make it pass compile, no useful.
UINT32 SYS_TUN_TYPE;

struct vdec_device*  g_decv_dev = NULL;
struct vdec_device*  g_decv_avc_dev = NULL;
struct vdec_device*  g_decv_avs_dev = NULL;
struct vdec_device*  g_decv_dev2 = NULL;
struct deca_device*  g_deca_dev  = NULL;
struct dmx_device*   g_dmx_dev = NULL;
struct dmx_device*   g_dmx_dev2 = NULL;
struct dmx_device*   g_dmx_dev3 = NULL;
struct nim_device*   g_nim_dev = NULL;
struct nim_device*   g_nim_dev2 = NULL;
struct snd_device*   g_snd_dev = NULL;
struct sdec_device*  g_sdec_dev = NULL;
struct vbi_device*   g_vbi_dev = NULL;
struct vbi_device*   g_vbi_dev2 = NULL;	//vicky20101229 dbg
struct ge_device*    g_ge_dev = NULL;
struct osd_device*   g_osd_dev = NULL;
struct osd_device*   g_osd_dev2 = NULL;
struct sto_device*   g_sto_dev = NULL;
struct vpo_device*   g_vpo_dev = NULL;
struct vpo_device*   g_sd_vpo_dev = NULL;
struct pan_device*   g_pan_dev = NULL;
struct rfm_device*   g_rfm_dev = NULL;
struct scart_device* g_scart_dev = NULL;
#if (defined(SUPPORT_VMX)||defined(SUPPORT_VMX_STD))
struct smc_device * g_smc_dev= NULL;
#endif
#if (ISDBT_CC ==1)
struct sdec_device*  g_isdbtcc_dec_dev = NULL;
#endif

#ifdef DVBT_BEE_TONE
volatile UINT8 beep_run = 0;
volatile UINT8 beep_cfged = 0;
#endif

T_VBIRequest VBIRequest;



int __errno;
unsigned short blogo_switch=0;
unsigned short blogo_tvformat=0;
unsigned short blogo_height=0;
UINT8   pre_tv_mode = 0xFF;
UINT8   pre_aspect_ratio = 0xFF;
extern UINT8  g_rgb_yuv_switch;
UINT32 app_uart_id = SCI_FOR_RS232;
int m_boot_vpo_active = 0;
struct vpo_io_logo_info logo_info;
extern void api_Scart_Aspect_Switch(UINT8 sw);

#ifdef  SUBT_FUNC_POINTER_ENABLE
#include <api/libsubt/subt_osd.h>
extern osd_subt_create_region_t	osd_subt_create_region;
extern osd_subt_delete_region_t	osd_subt_delete_region;
extern osd_subt_region_show_t	osd_subt_region_show;
extern osd_subt_draw_pixel_t	osd_subt_draw_pixel;
extern osd_region_is_created_t	osd_region_is_created;
extern osd_subt_draw_pixelmap_t	osd_subt_draw_pixelmap;
#endif

#ifdef _RD_DEBUG_
void process_monitor(void);
#endif

#ifdef PVR_FS_ZH
// For file system
static WORD vfs_mutex_id = INVALID_ID;

static void file_sys_lock()
{
	if(vfs_mutex_id == INVALID_ID)
		vfs_mutex_id = osal_mutex_create();
    if(vfs_mutex_id != INVALID_ID)
        osal_mutex_lock(vfs_mutex_id,OSAL_WAIT_FOREVER_TIME);	
}

static void file_sys_unlock()
{
    osal_mutex_unlock(vfs_mutex_id);	
}

static void init_file_system()
{
	static FS_PARAM fs_param = 
	{
	    file_sys_lock,	
		file_sys_unlock,
		malloc,
		free,
	};
	/* Install VFS filesystem */
	if(vfs_init(&fs_param) != SUCCESS) 
	{
		libc_printf("Init VFS failed\n");
		//asm("sdbbp");
	}
	/* Install VFAT module */
	if( fs_vfat_init(2) != SUCCESS) 
	{
       	libc_printf("Init VFAT failed\n");
		//asm("sdbbp");
	}    

    if( fs_ntfs_init(3) != SUCCESS) 
	{
       	libc_printf("Init NTFS failed\n");
		//asm("sdbbp");
	}

}
#endif

#ifdef HDTV_SUPPORT
/********************************************************************************
*				Pls follow the release rule as following									*
*	when want to release code or bin file to customer									*
*	1. Set the vendor name, and product description  									*
*	2. Assigned the gpio pin number for AT88SC0404C I2C_SCL and I2C_SDA  				*
*	3. For mass production, customer should assigned password( 3 bytes ) 					*
*         and Secret Seed ( 8 bytes ) array. 												*
*	    The assigned password/secret seed value should be the same with programmed in		*
*	    AT88SC0404C crypto memory.							 						*
*	   For piolt production, please leave these point to NULL								*
*********************************************************************************/
#ifdef HDCP_FROM_CE
RET_CODE ce_generate_hdcp()
{
	UINT16 i,j;
	UINT32 id = HDCPKEY_CHUNK_ID;
	UINT32 hdcp_chunk;
	UINT8 *hdcp_internal_keys;
	UINT8 temp_data[16];

	CE_DATA_INFO Ce_data_info ;
	pOTP_PARAM opt_info;
	pCE_DEVICE ce_dev = (pCE_DEVICE)dev_get_by_type(NULL, HLD_DEV_TYPE_CE);
	CE_DEBUG_KEY_INFO	ce_param;

    MEMSET(&Ce_data_info,0,sizeof(CE_DATA_INFO));    

	opt_info = MALLOC(sizeof(OTP_PARAM));
	MEMSET(opt_info ,0 , sizeof(OTP_PARAM) );
	
	opt_info->otp_addr = OTP_ADDESS_4; // load m2m2
	opt_info->otp_key_pos = KEY_0_3;
	
	if( RET_SUCCESS != ce_key_load(ce_dev , opt_info))
	{
		FREE( opt_info );
		return !RET_SUCCESS;	
	}

				
	hdcp_internal_keys = (UINT8 *)MALLOC(sizeof(UINT8)*288);
	hdcp_chunk = (UINT32)sto_chunk_goto(&id,0xFFFFFFFF,1);
	sto_get_data( (struct sto_device *)dev_get_by_id(HLD_DEV_TYPE_STO, 0), hdcp_internal_keys,
		hdcp_chunk+ CHUNK_HEADER_SIZE, 288);
	for(i=0;i<18;i++)
	{
		MEMCPY(temp_data,(hdcp_internal_keys+i*16),16);

		MEMCPY(&(Ce_data_info.otp_info),opt_info,sizeof(OTP_PARAM));
		Ce_data_info.data_info.data_len 				= 16;
		Ce_data_info.des_aes_info.aes_or_des 		= CE_SELECT_AES ; 	
		Ce_data_info.des_aes_info.crypt_mode 		= CE_IS_DECRYPT; 	
		Ce_data_info.des_aes_info.des_low_or_high 	= 0;					
		Ce_data_info.key_info.first_key_pos 			= KEY_0_3;
		Ce_data_info.key_info.hdcp_mode 			= TARGET_IS_HDCP_KEY_SRAM; 
		Ce_data_info.key_info.second_key_pos 		= i; 
		MEMCPY(Ce_data_info.data_info.crypt_data,temp_data,16);
	
		if(RET_SUCCESS != ce_generate_single_level_key(ce_dev, &Ce_data_info))
		{
			FREE( opt_info );
			FREE(hdcp_internal_keys);
			return !RET_SUCCESS;
		}
#if 0//for debug
		ce_param.len = 4; 
		ce_param.sel = HDCP_KEY_READ ;
		ce_ioctl(ce_dev,IO_CRYPT_DEBUG_GET_KEY,&ce_param);  
		osal_task_sleep(100);
		libc_printf("hdcp %08x,%08x,%08x,%08x\n",ce_param.buffer[0],ce_param.buffer[1],ce_param.buffer[2],ce_param.buffer[3]);
#endif
	}

	FREE( opt_info );
	FREE(hdcp_internal_keys);
	return RET_SUCCESS;
}
#endif
#endif

#ifdef NETWORK_SUPPORT
void network_attach()
{
#if (defined(IDE_SUPPORT) || defined(SDIO_SUPPORT) || \
 (defined(NETWORK_SUPPORT) && (SYS_NETWORK_MODULE == SMSC9220)))
	if (sys_ic_get_chip_id() < ALI_S3602F)
	{
		//ATA share pins with flash, disable flash.
		*((volatile UINT32 *)0xb8000090) = (*((volatile UINT32 *)0xb8000090) & 0xf0) | 0x02;

		//Set Pin Mux. 
		*((volatile UINT32 *)0xb8000088) |= 0x000000a1;
	}
#endif


	static UINT8 mac_addr[] = {0x00, 0x1E, 0x90, 0x22, 0x53, 0x59};

#if (SYS_NETWORK_MODULE == SMSC9220)

// GPIO for SMSC9220
#define SMSC9220_A6_GPIO_NUM		31
#define SMSC9220_A7_GPIO_NUM		32
#define SMSC9220_CS_GPIO_NUM		33
#define SMSC9220_FIFO_SEL_GPIO_NUM	34
#define SMSC9220_INT_GPIO_NUM		35

	//Set Pin Mux. 
	*((volatile UINT32 *)0xb8000088) |= 0x1000; /* select GPIO[31-35] */
	*((volatile UINT8  *)0xb800008c) &= (~0x04);

//	HAL_GPIO_BIT_DIR_SET(25, HAL_GPIO_O_DIR);
//	HAL_GPIO_BIT_SET(25, 1); /* de-select SD Card */
//	HAL_GPIO_BIT_DIR_SET(SMSC9220_CS_GPIO_NUM, HAL_GPIO_O_DIR); /* LAN_nCS */
//	HAL_GPIO_BIT_SET(SMSC9220_CS_GPIO_NUM, 0);

	SMSC_CONFIG smsc_cfg;
	MEMSET(&smsc_cfg, 0, sizeof(SMSC_CONFIG));
	smsc_cfg.en_gpio_setting = 1;
	smsc_cfg.a6_gpio_position = SMSC9220_A6_GPIO_NUM;
	smsc_cfg.a7_gpio_position = SMSC9220_A7_GPIO_NUM;
	smsc_cfg.cs_gpio_position = SMSC9220_CS_GPIO_NUM;
	smsc_cfg.sel_gpio_position = SMSC9220_FIFO_SEL_GPIO_NUM;
	smsc_cfg.int_gpio_position = SMSC9220_INT_GPIO_NUM;
	smsc_cfg.int_gpio_polar = 0;
   
	smsc_cfg.en_ata_setting = 1;
	smsc_cfg.ata_timing = 0x02190900; // ATA timing for PIO transfer mode

	smsc_cfg.en_mac_setting = 0;		// 0: system get MAC address from erom; 1: SW config MAC address
	MEMCPY(smsc_cfg.mac_addr, mac_addr, sizeof(mac_addr));
   
	smsc9220_attach(&smsc_cfg);

#elif (SYS_NETWORK_MODULE == NET_ENC28J60)

	ENC_CONFIG enc_cfg;
	MEMSET(&enc_cfg, 0, sizeof(ENC_CONFIG));	
	enc_cfg.init_mac_addr = 1;
	MEMCPY(enc_cfg.mac_addr, mac_addr, sizeof(mac_addr));
/*
	enc_cfg.int_by_gpio = 1; // use interrupt
	enc_cfg.int_position = 54; // depends on board design
	enc_cfg.int_io = HAL_GPIO_I_DIR;
	enc_cfg.int_polar = 0; // depends on board design
	enc_cfg.link_mode = NET_LINK_FULL; // If the net environment is half-duplex, then don't set this field.
*/
	net_enc28j60_attach(&enc_cfg);
#elif (SYS_NETWORK_MODULE == NET_ALIETHMAC)

	MAC_CONFIG mac_cfg;
	MEMSET(&mac_cfg, 0, sizeof(MAC_CONFIG));	

	mac_cfg.mac_addr[0] = 0x00;
	mac_cfg.mac_addr[1] = 0x55;
	mac_cfg.mac_addr[2] = 0x66;
	mac_cfg.mac_addr[3] = 0x77;
	mac_cfg.mac_addr[4] = 0x88;
	mac_cfg.mac_addr[5] = 0x99;
	//Set phy address
	mac_cfg.phy_addr = 0x05;

	//Set phy mode to RMII
	mac_cfg.phy_mode = NET_PHY_RMII;
#ifndef MAC_TEST
	eth_mac_attach(&mac_cfg);
#endif

#endif

#ifdef WIFI_SUPPORT
	WiFi_attach();
#endif
#if (defined WIFI_P2P_SUPPORT || defined ALICAST_SUPPORT)
    p2p_attach();
#ifdef WIFI_DIRECT_SUPPORT
    extern void wifi_direct_register_callback(void);
    wifi_direct_register_callback();
#endif    
#endif

}
#endif



/********************Tmp Example for Application Begin********************/
void InitVPPara(struct VP_InitInfo *pVPInitInfo)
{
	int i;
    BOOL vdac_progressive = FALSE;

	//api set backgound color]
	pVPInitInfo->tInitColor.uY = 0x10;
	pVPInitInfo->tInitColor.uCb= 0x80;
	pVPInitInfo->tInitColor.uCr= 0x80;

	//set advanced control
	pVPInitInfo->bBrightnessValue = 0;
	pVPInitInfo->fBrightnessValueSign = TRUE;
	pVPInitInfo->wContrastValue = 0;
	pVPInitInfo->fContrastSign = TRUE;
	pVPInitInfo->wSaturationValue = 0;
	pVPInitInfo->fSaturationValueSign = TRUE;
	pVPInitInfo->wSharpness = 0;
	pVPInitInfo->fSharpnessSign = TRUE;
	pVPInitInfo->wHueSin = 0;
	pVPInitInfo->fHueSinSign = TRUE;
	pVPInitInfo->wHueCos = 0;
	pVPInitInfo->fHueCosSign = TRUE;
	pVPInitInfo->bCCIR656Enable = FALSE;
	//VPO_Zoom
	pVPInitInfo->tSrcRect.uStartX = 0;
	pVPInitInfo->tSrcRect.uWidth= PICTURE_WIDTH;
	pVPInitInfo->tSrcRect.uStartY= 0;
	pVPInitInfo->tSrcRect.uHeight= PICTURE_HEIGHT;
	pVPInitInfo->DstRect.uStartX = 0;
	pVPInitInfo->DstRect.uWidth= SCREEN_WIDTH;
	pVPInitInfo->DstRect.uStartY= 0;
	pVPInitInfo->DstRect.uHeight= SCREEN_HEIGHT;

	//VPO_SetAspect
	if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
	{
        if(pre_tv_mode == 0xFF)
		{
            //pVPInitInfo->eTVAspect = TV_16_9;
            //pVPInitInfo->eDisplayMode = PILLBOX;
            pVPInitInfo->eTVAspect = TV_4_3;// aspect default set to auto,eTVAspect set to TV_4_3 when avset.tv_ratio is auto
            pVPInitInfo->eDisplayMode = NORMAL_SCALE;
        }
        else
        {
            pVPInitInfo->eTVAspect = (sys_data_get_aspect_mode() ==TV_ASPECT_RATIO_169)? TV_16_9 : TV_4_3;
            pVPInitInfo->eDisplayMode = sys_data_get_display_mode();
            pre_aspect_ratio = sys_data_get_aspect_mode();
        }
	}
    else
    {
    	pVPInitInfo->eTVAspect = TV_4_3;
        pVPInitInfo->eDisplayMode = NORMAL_SCALE;
    }
	pVPInitInfo->uNonlinearChangePoint = 111;
	pVPInitInfo->uPanScanOffset = 90;
	//VPO_SetOutput
	for(i=0;i<VP_DAC_TYPENUM;i++)
		pVPInitInfo->pDacConfig[i].bEnable = FALSE;
#if 0
	pVPInitInfo->pDacConfig[CVBS_1].bEnable = TRUE;
	pVPInitInfo->pDacConfig[CVBS_1].tDacIndex.uDacFirst =DAC0;
	pVPInitInfo->pDacConfig[CVBS_1].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[CVBS_1].bProgressive= FALSE;
	
	pVPInitInfo->pDacConfig[CVBS_2].bEnable = TRUE;
	pVPInitInfo->pDacConfig[CVBS_2].tDacIndex.uDacFirst = DAC1;
	pVPInitInfo->pDacConfig[CVBS_2].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[CVBS_2].bProgressive= FALSE;

	pVPInitInfo->pDacConfig[CVBS_3].bEnable = TRUE;
	pVPInitInfo->pDacConfig[CVBS_3].tDacIndex.uDacFirst = DAC2;
	pVPInitInfo->pDacConfig[CVBS_3].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[CVBS_3].bProgressive= FALSE;

	pVPInitInfo->pDacConfig[CVBS_4].bEnable = TRUE;
	pVPInitInfo->pDacConfig[CVBS_4].tDacIndex.uDacFirst = DAC3;
	pVPInitInfo->pDacConfig[CVBS_4].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[CVBS_4].bProgressive= FALSE;
#endif

//CVBS_1
#ifdef VDAC_USE_CVBS_TYPE
#ifdef _S3281_
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = TRUE;
#else
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = FALSE;
#endif	
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].tDacIndex.uDacFirst = CVBS_DAC;
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bProgressive= FALSE;
#endif

//YC
#ifdef VDAC_USE_SVIDEO_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_SVIDEO_TYPE].bEnable = TRUE;
	pVPInitInfo->pDacConfig[VDAC_USE_SVIDEO_TYPE].tDacIndex.uDacFirst = SVIDEO_DAC_Y;
	pVPInitInfo->pDacConfig[VDAC_USE_SVIDEO_TYPE].tDacIndex.uDacSecond= SVIDEO_DAC_C;
	pVPInitInfo->pDacConfig[VDAC_USE_SVIDEO_TYPE].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[VDAC_USE_SVIDEO_TYPE].bProgressive= FALSE;
#endif

//YUV
#ifdef VDAC_USE_YUV_TYPE
	pVPInitInfo->pDacConfig[YUV_1].bEnable = TRUE;
	pVPInitInfo->pDacConfig[YUV_1].tDacIndex.uDacFirst = YUV_DAC_Y;
	pVPInitInfo->pDacConfig[YUV_1].tDacIndex.uDacSecond= YUV_DAC_U;
	pVPInitInfo->pDacConfig[YUV_1].tDacIndex.uDacThird= YUV_DAC_V;
	pVPInitInfo->pDacConfig[YUV_1].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[YUV_1].bProgressive= FALSE;
#endif

//RGB
#ifdef VDAC_USE_RGB_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].bEnable = TRUE;
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].tDacIndex.uDacFirst = RGB_DAC_R;
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].tDacIndex.uDacSecond= RGB_DAC_G;
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].tDacIndex.uDacThird= RGB_DAC_B;
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].bProgressive= FALSE;
#endif

    if (sys_data_get_scart_out() == SCART_YUV)
    {
#if defined(DUAL_VIDEO_OUTPUT) || defined(DUAL_VIDEO_OUTPUT_USE_VCAP)       
    	if(pre_tv_mode == 0xFF)
		{
			if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
			{
				pre_tv_mode = LINE_1080_25;
			}
			else
			{
    			pre_tv_mode = LINE_720_30;//PAL;
			}
		}
#else
    	if(pre_tv_mode == 0xFF)
    		pre_tv_mode = PAL;
#endif
    	pVPInitInfo->eTVSys = pre_tv_mode;

        if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
        {
            vdac_progressive = sys_data_is_progressive(sys_data_get_TV_mode());
        }
        else
        {
            if (pre_tv_mode == LINE_720_30 || pre_tv_mode == LINE_720_25
                || pre_tv_mode == LINE_1080_50 || pre_tv_mode == LINE_1080_60 || pre_tv_mode == LINE_1080_24
                )
                vdac_progressive = TRUE;
        }
        
#ifdef VDAC_USE_CVBS_TYPE
#if defined(DUAL_VIDEO_OUTPUT) || defined(DUAL_VIDEO_OUTPUT_USE_VCAP)
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = FALSE;
    if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
    {
        if((sys_data_get_TV_mode() == TV_MODE_PAL)||(sys_data_get_TV_mode() == TV_MODE_NTSC358))
        {
            pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = TRUE;
        }
    }
#else
    if (pre_tv_mode == PAL || pre_tv_mode == NTSC || pre_tv_mode == NTSC_443)
        pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = TRUE;
    else
        pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = FALSE;
#endif
#endif
#ifdef VDAC_USE_YUV_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_YUV_TYPE].bEnable = TRUE;
    pVPInitInfo->pDacConfig[VDAC_USE_YUV_TYPE].bProgressive = vdac_progressive;
#endif
#ifdef VDAC_USE_RGB_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].bEnable = FALSE;
#endif
    }
    else
    {
        if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
        {
            if(pre_tv_mode == 0xFF)
            {
                pVPInitInfo->eTVSys = PAL;
            }
            else
            {
                if(sys_data_get_TV_mode() == TV_MODE_AUTO && pre_tv_mode >= LINE_720_25)
                {
                    pVPInitInfo->eTVSys = tvsys_hd_to_sd(pre_tv_mode);
                }
                else
                {
                    pVPInitInfo->eTVSys = pre_tv_mode;
                }
            }
        }
        else
        {
            pVPInitInfo->eTVSys = PAL;
        }

#ifdef VDAC_USE_CVBS_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = TRUE;
#endif
#ifdef VDAC_USE_YUV_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_YUV_TYPE].bEnable = FALSE;
#endif
#ifdef VDAC_USE_RGB_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].bEnable = TRUE;
#endif
    }

	pVPInitInfo->bWinOnOff = FALSE;
	pVPInitInfo->uWinMode = VPO_MAINWIN;//|VPO_PIPWIN;
	pVPInitInfo->tPIPCallBack.RequestCallback = NULL;
	pVPInitInfo->tPIPCallBack.ReleaseCallback= NULL;
#ifndef DUAL_ENABLE
#if (SYS_CHIP_MODULE == ALI_S3602)
#ifndef _BUILD_OTA_E_
	pVPInitInfo->tMPCallBack.RequestCallback = (T_MPRequest)vdec_s3601_de_request;
	pVPInitInfo->tMPCallBack.ReleaseCallback = (T_MPRelease)vdec_s3601_de_release;
#endif
#else
	pVPInitInfo->tMPCallBack.RequestCallback = vdec_m3327_de_mp_request;
	pVPInitInfo->tMPCallBack.ReleaseCallback= vdec_m3327_de_mp_release;
#endif
#endif
	pVPInitInfo->pSrcChange_CallBack=NULL;
}

void InitVPPara_sd(struct VP_InitInfo *pVPInitInfo)
{
	int i;

	MEMSET(pVPInitInfo, 0, sizeof(struct VP_InitInfo));

#ifdef DUAL_VIDEO_OUTPUT_USE_VCAP
    pVPInitInfo->device_priority = VPO_AUTO_DUAL_OUTPUT;    // S3602F use VCAP
#else
	pVPInitInfo->device_priority = VPO_INDEPENDENT_IN_OUT;  // M3602 use old methed
#endif

	//api set backgound color]
	pVPInitInfo->tInitColor.uY = 0x10;
	pVPInitInfo->tInitColor.uCb= 0x80;
	pVPInitInfo->tInitColor.uCr= 0x80;

	//set advanced control
	pVPInitInfo->bBrightnessValue = 0;
	pVPInitInfo->fBrightnessValueSign = TRUE;
	pVPInitInfo->wContrastValue = 0;
	pVPInitInfo->fContrastSign = TRUE;
	pVPInitInfo->wSaturationValue = 0;
	pVPInitInfo->fSaturationValueSign = TRUE;
	pVPInitInfo->wSharpness = 0;
	pVPInitInfo->fSharpnessSign = TRUE;
	pVPInitInfo->wHueSin = 0;
	pVPInitInfo->fHueSinSign = TRUE;
	pVPInitInfo->wHueCos = 0;
	pVPInitInfo->fHueCosSign = TRUE;
	//VPO_Zoom
	pVPInitInfo->tSrcRect.uStartX = 0;
	pVPInitInfo->tSrcRect.uWidth= PICTURE_WIDTH;
	pVPInitInfo->tSrcRect.uStartY= 0;
	pVPInitInfo->tSrcRect.uHeight= PICTURE_HEIGHT;
	pVPInitInfo->DstRect.uStartX = 0;
	pVPInitInfo->DstRect.uWidth= SCREEN_WIDTH;
	pVPInitInfo->DstRect.uStartY= 0;
	pVPInitInfo->DstRect.uHeight= SCREEN_HEIGHT;

	//VPO_SetAspect
	if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
	{
        if(pre_aspect_ratio == 0xFF)
		{
            //pVPInitInfo->eTVAspect = TV_16_9;
            //pVPInitInfo->eDisplayMode = PILLBOX;
            pVPInitInfo->eTVAspect = TV_4_3;// aspect default set to auto,eTVAspect set to TV_4_3 when avset.tv_ratio is auto
            pVPInitInfo->eDisplayMode = NORMAL_SCALE;
            
        }
        else
        {
            pVPInitInfo->eTVAspect = (sys_data_get_aspect_mode() ==TV_ASPECT_RATIO_169)? TV_16_9 : TV_4_3;
            pVPInitInfo->eDisplayMode = sys_data_get_display_mode();
        }
	}
    else
    {
    	pVPInitInfo->eTVAspect = TV_4_3;
        pVPInitInfo->eDisplayMode = NORMAL_SCALE;
    }

    //pVPInitInfo->eDisplayMode = NORMAL_SCALE;//LETTERBOX;
	pVPInitInfo->uNonlinearChangePoint = 111;
	pVPInitInfo->uPanScanOffset = 90;
	//VPO_SetOutput
	for(i=0;i<VP_DAC_TYPENUM;i++)
		pVPInitInfo->pDacConfig[i].bEnable = FALSE;

//CVBS_1
#ifdef VDAC_USE_CVBS_TYPE
   	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = TRUE;
    if (sys_data_get_scart_out() == SCART_YUV)
    {
        if((m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
            && ((sys_data_get_TV_mode() == TV_MODE_PAL)||(sys_data_get_TV_mode() == TV_MODE_NTSC358)))
        {
            pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bEnable = FALSE;
        }
    	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].tDacIndex.uDacFirst = CVBS_DAC;
    }
    else
    {
    	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].tDacIndex.uDacFirst = 0xFF;
    }
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].eVGAMode= VGA_NOT_USE;
	pVPInitInfo->pDacConfig[VDAC_USE_CVBS_TYPE].bProgressive= FALSE;
#endif

	//YC
#ifdef VDAC_USE_SVIDEO_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_SVIDEO_TYPE].bEnable = FALSE;
#endif
	
	//YUV
#ifdef VDAC_USE_YUV_TYPE
	pVPInitInfo->pDacConfig[YUV_1].bEnable = FALSE;
#endif
	
	//RGB
#ifdef VDAC_USE_RGB_TYPE
	pVPInitInfo->pDacConfig[VDAC_USE_RGB_TYPE].bEnable = FALSE;
#endif
	
	if(blogo_switch)
	{
		if(blogo_tvformat==LOGO_FORMAT_PAL)
			pVPInitInfo->eTVSys = PAL;
		else if (blogo_tvformat==LOGO_FORMAT_PAL_N)
			pVPInitInfo->eTVSys = PAL_N;
		else if(blogo_tvformat==LOGO_FORMAT_NTSC)
			pVPInitInfo->eTVSys = NTSC;
		else if(blogo_tvformat==LOGO_FORMAT_PAL_M)
			pVPInitInfo->eTVSys = PAL_M;
		else if(blogo_tvformat==LOGO_FORMAT_PAL_60)
			pVPInitInfo->eTVSys =PAL_60;
		else if(blogo_tvformat==LOGO_FORMAT_NTSC_443)
			pVPInitInfo->eTVSys = NTSC_443;
		pVPInitInfo->bWinOnOff = TRUE;
	}
	else
	{
      if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
      {
            if(pre_tv_mode == 0xFF)
            {
                pVPInitInfo->eTVSys = PAL;
            }
            else
            {
                pVPInitInfo->eTVSys = tvsys_hd_to_sd(pre_tv_mode);
            }        
      }
      else
      {
#ifdef DUAL_VIDEO_OUTPUT_USE_VCAP
            pVPInitInfo->eTVSys = NTSC;
#else
            pVPInitInfo->eTVSys = PAL;
#endif
      }
		pVPInitInfo->bWinOnOff = FALSE;
	}

	pVPInitInfo->uWinMode = VPO_MAINWIN;//|VPO_PIPWIN;
	pVPInitInfo->tPIPCallBack.RequestCallback = NULL;
	pVPInitInfo->tPIPCallBack.ReleaseCallback= NULL;
#ifndef DUAL_ENABLE
#ifndef USE_NEW_VDEC
	pVPInitInfo->tMPCallBack.RequestCallback = VDec_Output_Frame;
	pVPInitInfo->tMPCallBack.ReleaseCallback= VDec_Release_FrBuf;
#else
#if (SYS_CHIP_MODULE == ALI_S3601 || SYS_CHIP_MODULE == ALI_S3602)
#ifndef _BUILD_OTA_E_
	pVPInitInfo->tMPCallBack.RequestCallback = (T_MPRequest)vdec_s3601_de_request;
	pVPInitInfo->tMPCallBack.ReleaseCallback = (T_MPRelease)vdec_s3601_de_release;
#endif
#else
	pVPInitInfo->tMPCallBack.RequestCallback = vdec_m3327_de_mp_request;
	pVPInitInfo->tMPCallBack.ReleaseCallback= vdec_m3327_de_mp_release;
#endif
#endif
#endif
	pVPInitInfo->pSrcChange_CallBack=NULL;
}



void avStart()
{
	struct VDecPIPInfo vInitInfo;
	struct MPSource_CallBack vMPCallBack;
	struct PIPSource_CallBack vPIPCallBack;
	struct VDec_PullDown_Opr tPullDownCallBack;
    struct vp_win_config_para win_para;

    MEMSET(&vInitInfo, 0, sizeof(vInitInfo));
    MEMSET(&vMPCallBack, 0, sizeof(vMPCallBack));
    MEMSET(&vPIPCallBack, 0, sizeof(vPIPCallBack));
    MEMSET(&tPullDownCallBack, 0, sizeof(tPullDownCallBack));

	PRINTF("NIM OK\n");
	dmx_start(g_dmx_dev);
#ifdef NEW_DEMO_FRAME
	dmx_start(g_dmx_dev2);
#endif

#ifdef HDTV_SUPPORT
	vdec_profile_level(g_decv_dev, MP_HL, NULL);
	enum TVSystem  tvsys;
	vpo_ioctl(g_vpo_dev, VPO_IO_GET_OUT_MODE, (UINT32) &tvsys);
	
	vInitInfo.adv_setting.init_mode =0;
    if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
    {
       if(pre_tv_mode == 0xff)
       {
            vInitInfo.adv_setting.out_sys = LINE_1080_25;
            vInitInfo.adv_setting.bprogressive = FALSE;
       }
       else
       {
            if(sys_data_get_TV_mode() == TV_MODE_AUTO
                && sys_data_get_scart_out() == SCART_RGB
                && pre_tv_mode >= LINE_720_25)
            {
                vInitInfo.adv_setting.out_sys = tvsys_hd_to_sd(pre_tv_mode);
                vInitInfo.adv_setting.bprogressive = FALSE;
            }
            else
            {
               vInitInfo.adv_setting.out_sys = sys_data_to_tv_mode(sys_data_get_TV_mode());
               vInitInfo.adv_setting.bprogressive = sys_data_is_progressive(sys_data_get_TV_mode());
            }
       }
    }
    else
    {
    	vInitInfo.adv_setting.out_sys = tvsys;
        if(tvsys == LINE_720_30)
        {
            vInitInfo.adv_setting.bprogressive = TRUE;
        }
    }
    
#ifdef DUAL_VIDEO_OUTPUT
	vdec_set_output(g_decv_dev,	DUAL_MODE, &vInitInfo, &vMPCallBack, &vPIPCallBack);
#ifndef _BUILD_OTA_E_
    video_set_output(DUAL_MODE, &vInitInfo);
#endif
	
	win_para.source_number = 1;
	win_para.control_source_index = 0;
	win_para.source_info[0].attach_source_index = 1;
	win_para.source_info[0].src_callback.request_callback = (T_Request)(vMPCallBack.RequestCallback);
	win_para.source_info[0].src_callback.release_callback = (T_Release)(vMPCallBack.ReleaseCallback);
	win_para.source_info[0].src_callback.vblanking_callback= vMPCallBack.vblanking_callback;
	win_para.source_info[0].src_module_devide_handle = g_decv_dev;
	win_para.source_info[0].src_path_index = 1;
	win_para.window_number = 1;
	win_para.window_parameter[0].source_index = 0;
	win_para.window_parameter[0].display_layer = VPO_LAYER_MAIN;
/*	win_para.window_parameter[0].rect.src_rect.uStartX = 0;
	win_para.window_parameter[0].rect.src_rect.uStartY = 0;
	win_para.window_parameter[0].rect.src_rect.uWidth = PICTURE_WIDTH;
	win_para.window_parameter[0].rect.src_rect.uHeight = PICTURE_HEIGHT;	
	win_para.window_parameter[0].rect.dst_rect.uStartX = 0;
	win_para.window_parameter[0].rect.dst_rect.uStartY = 0;
	win_para.window_parameter[0].rect.dst_rect.uWidth = SCREEN_WIDTH;
	win_para.window_parameter[0].rect.dst_rect.uHeight = SCREEN_HEIGHT;*/
	vpo_config_source_window(g_sd_vpo_dev, &win_para);
	
#else
	vdec_set_output(g_decv_dev,	MP_MODE, &vInitInfo, &vMPCallBack, &vPIPCallBack);
#ifndef _BUILD_OTA_E_
    video_set_output(MP_MODE, &vInitInfo);
#endif
#endif
#else
	vdec_set_output(g_decv_dev,	MP_MODE, &vInitInfo, &vMPCallBack, &vPIPCallBack);
#ifndef _BUILD_OTA_E_
    video_set_output(MP_MODE, &vInitInfo);
#endif
#endif
    hde_set_mode(VIEW_MODE_FULL);
	//if(RET_SUCCESS!= VDec_Decode(0,ALL_PIC,	FALSE,0,FALSE,FALSE,FALSE))
	//	ASSERT(0);
	vpo_win_mode(g_vpo_dev, VPO_MAINWIN, &vMPCallBack, &vPIPCallBack);
#ifdef VDEC_AV_SYNC
	 vdec_sync_mode(g_decv_dev, 0x00,VDEC_SYNC_I|VDEC_SYNC_P|VDEC_SYNC_B);
	deca_set_sync_mode(g_deca_dev, ADEC_SYNC_PTS);
#endif

#if	(TTX_ON == 1)
    if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
    {
        if((sys_data_get_scart_out() == SCART_RGB) 
            || ((sys_data_get_scart_out() == SCART_YUV)
            && ((sys_data_get_TV_mode() == TV_MODE_PAL)
            || (sys_data_get_TV_mode() == TV_MODE_NTSC358))))
        {
            vbi_ioctl(g_vbi_dev, IO_VBI_SELECT_OUTPUT_DEVICE, 0);
            vbi_setoutput(g_vbi_dev, &VBIRequest);
            vpo_ioctl(g_vpo_dev, VPO_IO_SET_VBI_OUT, (UINT32)VBIRequest);
            if(g_sd_vpo_dev != NULL)
                vpo_ioctl(g_sd_vpo_dev, VPO_IO_SET_VBI_OUT, NULL);
        }
        else
        {
            vbi_ioctl(g_vbi_dev, IO_VBI_SELECT_OUTPUT_DEVICE, 1);
            vbi_setoutput(g_vbi_dev, &VBIRequest);
            vpo_ioctl(g_vpo_dev, VPO_IO_SET_VBI_OUT, NULL);
            if(g_sd_vpo_dev != NULL)
                vpo_ioctl(g_sd_vpo_dev, VPO_IO_SET_VBI_OUT, (UINT32)VBIRequest);
        }
    }
    else
    {
    	vbi_setoutput(g_vbi_dev, &VBIRequest);
    	vpo_ioctl(g_vpo_dev, VPO_IO_SET_VBI_OUT, (UINT32)VBIRequest);
    }

#ifdef HDTV_SUPPORT   
    if(PAL != tvsys_hd_to_sd(tvsys))
        enable_vbi_transfer(FALSE);//cloud
#endif

#endif

#if (CC_ON==1)
    if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
    {
        if((sys_data_get_scart_out() == SCART_RGB) 
            || ((sys_data_get_scart_out() == SCART_YUV)
            && ((sys_data_get_TV_mode() == TV_MODE_PAL)
            || (sys_data_get_TV_mode() == TV_MODE_NTSC358))))
        {
            vbi_setoutput(g_vbi_dev2, &VBIRequest); //vicky20101229 dbg
        	vpo_ioctl(g_vpo_dev, VPO_IO_SET_VBI_OUT, (UINT32)VBIRequest);
        	vpo_ioctl(g_vpo_dev, VPO_IO_SD_CC_ENABLE,TRUE);
        }
        else
        {
            vbi_setoutput(g_vbi_dev2, &VBIRequest); //vicky20101229 dbg
            if(g_sd_vpo_dev != NULL)
            {
              	vpo_ioctl(g_sd_vpo_dev, VPO_IO_SET_VBI_OUT, (UINT32)VBIRequest);
                vpo_ioctl(g_sd_vpo_dev, VPO_IO_SD_CC_ENABLE,TRUE);
            }
            else
            {
                vpo_ioctl(g_vpo_dev, VPO_IO_SET_VBI_OUT, (UINT32)VBIRequest);
    	        vpo_ioctl(g_vpo_dev, VPO_IO_SD_CC_ENABLE,TRUE);
            }
        }
    }
    else
    {
    	vbi_setoutput(g_vbi_dev2, &VBIRequest); //vicky20101229 dbg
    	vpo_ioctl(g_vpo_dev, VPO_IO_SET_VBI_OUT, (UINT32)VBIRequest);
    	vpo_ioctl(g_vpo_dev, VPO_IO_SD_CC_ENABLE,TRUE);
    }
#endif

#ifdef DO_DDP_CERTIFICATION
    // DD+ not need io control
    //deca_io_control(g_deca_dev, DECA_DO_DDP_CERTIFICATION, 1);
    //snd_io_control(g_snd_dev, SND_DO_DDP_CERTIFICATION, 1);
#endif
#ifdef FULL_SCREEN_CVBS
    vpo_ioctl(g_vpo_dev, VPO_FULL_SCREEN_CVBS,1);
#endif

    if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
    {
        vpo_ioctl(g_vpo_dev, VPO_IO_BOOT_UP_DONE, 1);
    }
}

RET_CODE avInit()
{
	OSAL_ID tsk_id = OSAL_INVALID_ID;
	OSAL_T_CTSK t_ctsk;
	struct VP_InitInfo	tVPInitInfo;
	struct snd_output_cfg cfg_param;

	MEMSET(&tVPInitInfo, 0, sizeof(struct VP_InitInfo));

	t_ctsk.stksz = 0x1000;
	t_ctsk.quantum = 10;

	g_deca_dev = (struct deca_device *)dev_get_by_id(HLD_DEV_TYPE_DECA, 0);
	g_dmx_dev = (struct dmx_device *)dev_get_by_id(HLD_DEV_TYPE_DMX, 0);
	g_dmx_dev2 = (struct dmx_device *)dev_get_by_id(HLD_DEV_TYPE_DMX, 1);
	g_dmx_dev3 =  (struct dmx_device *)dev_get_by_id(HLD_DEV_TYPE_DMX, 2);
	g_snd_dev = (struct snd_device *)dev_get_by_id(HLD_DEV_TYPE_SND, 0);
	g_vpo_dev = (struct vpo_device *)dev_get_by_id(HLD_DEV_TYPE_DIS, 0);
    g_sd_vpo_dev = (struct vpo_device *)dev_get_by_id(HLD_DEV_TYPE_DIS, 1);
	g_decv_dev = (struct vdec_device *)dev_get_by_id(HLD_DEV_TYPE_DECV, 0);
	g_decv_avc_dev = (struct vdec_device *)dev_get_by_name("DECV_AVC_0");
	g_decv_dev2 = (struct vdec_device *)dev_get_by_id(HLD_DEV_TYPE_DECV, 1);
	g_decv_avs_dev = (struct vdec_device *)dev_get_by_name("DECV_AVS_0");

#if	(SUBTITLE_ON == 1)
	g_sdec_dev = (struct sdec_device *)dev_get_by_name("SDEC_M3327_0");
#endif

#if	(TTX_ON == 1)
	g_vbi_dev = (struct vbi_device *)dev_get_by_id(HLD_DEV_TYPE_VBI, 0);
#endif

#if	(CC_ON == 1) //vicky20101229 dbg
   #if(TTX_ON!=1)
   g_vbi_dev2 = (struct vbi_device *)dev_get_by_id(HLD_DEV_TYPE_VBI, 0);
   #else
   g_vbi_dev2 = (struct vbi_device *)dev_get_by_id(HLD_DEV_TYPE_VBI, 1);
   #endif
#endif
#if	(ISDBT_CC == 1) 
	g_isdbtcc_dec_dev = (struct sdec_device *)dev_get_by_name("ISDBT_CC_0");
#endif

#if ((!(defined _S3281_||defined _M3503_||defined _M3821_|| defined _S3811_))||(!defined _BUILD_OTA_E_))//add by comer
	if(g_deca_dev==NULL||g_dmx_dev==NULL||g_snd_dev==NULL)
	{
		PRINTF("Get device point failed: g_deca_dev=%08x g_dmx_dev=%08x g_snd_dev=%08x\n", g_deca_dev, g_dmx_dev, g_snd_dev);
		ASSERT(0);
	}
#endif


#ifdef DVBT_BEE_TONE
#ifndef _S3281_
#if (defined _M3503_ || defined _M3821_)
#ifndef _BUILD_OTA_E_
	deca_m36_init_tone_voice(g_deca_dev);
	snd_m36g_init_tone_voice(g_snd_dev);
	snd_m36g_init_spectrum(g_snd_dev);
#endif
#else
#ifndef _BUILD_OTA_E_
	deca_m36_init_tone_voice(g_deca_dev);
	snd_m36_init_tone_voice(g_snd_dev);
	snd_init_spectrum(g_snd_dev);
#endif
#endif
#endif
#endif
#if ((!(defined _S3281_||defined _M3503_||defined _M3821_|| defined _S3811_))||(!defined _BUILD_OTA_E_))//add by comer
	if(RET_SUCCESS!=deca_open(g_deca_dev, AUDIO_MPEG2, AUDIO_SAMPLE_RATE_48, AUDIO_QWLEN_24, 2, 0))
	{
		PRINTF("deca_open failed!!\n");
		ASSERT(0);
	}
    
    deca_io_control((struct deca_device *)dev_get_by_id(HLD_DEV_TYPE_DECA, 0),DECA_DOLBY_SET_VOLUME_DB,1);  // Maybe sometimes can be removed,tnntc 2011-7-7
#endif
#ifdef _S3281_
#ifdef DVBT_BEE_TONE
      deca_io_control((struct deca_device * )dev_get_by_id(HLD_DEV_TYPE_DECA, 0), DECA_EABLE_INIT_TONE_VOICE, 0);
#endif
#ifdef DVR_PVR_SUPPORT
	  deca_io_control((struct deca_device * )dev_get_by_id(HLD_DEV_TYPE_DECA, 0), DECA_EABLE_DVR_ENABLE, 0);
#endif
#endif

#ifdef AUDIO_SPECIAL_EFFECT
	deca_init_ase(g_deca_dev);
#endif
	
#if (defined(_MHEG5_V20_ENABLE_))
 //    deca_init_ase(g_deca_dev);
#endif   
#if ((!(defined _S3281_||defined _M3503_||defined _M3821_|| defined _S3811_))||(!defined _BUILD_OTA_E_))//add by comer
	if(RET_SUCCESS!=snd_open(g_snd_dev))
	{
		PRINTF("snd_open failed!!\n");
		ASSERT(0);
	}
#endif
//    snd_io_control((struct deca_device *)dev_get_by_id(HLD_DEV_TYPE_SND, 0),SND_MPEG_M8DB_ENABLE,1);  // mpeg pcm data m8db

    // SE: Mute before scart power on to avoid noise
    api_audio_set_mute(TRUE);
	api_Scart_Power_OnOff(1);
    
	if (g_scart_dev)
	{
		if(scart_open(g_scart_dev) != RET_SUCCESS)
		{
			PRINTF("scart_open failed!!\n");
			//ASSERT(0);
			//scart_io_control(g_scart_dev,SCART_DETACH_DEV,0);//detach may cause dev list link see pointer
            g_scart_dev = NULL;
		}
	}

	api_Scart_TVSAT_Switch(0);
	//api_Scart_RGB_OnOff(0);/*CVBS mode*/

#if ((!(defined _S3281_||defined _M3503_||defined _M3821_|| defined _S3811_))||(!defined _BUILD_OTA_E_))//add by comer
	if(RET_SUCCESS!=vdec_open(g_decv_dev))
		ASSERT(0);	
#endif
#ifdef SUPPORT_CAS9		
    vdec_io_control(g_decv_dev, VDEC_IO_FIRST_I_FREERUN, TRUE);
    vdec_io_control(g_decv_avc_dev, VDEC_IO_FIRST_I_FREERUN, TRUE);
#endif	

#ifdef SLOW_PLAY_BEFORE_SYNC
    vdec_io_control(g_decv_avc_dev, VDEC_IO_SLOW_PLAY_BEFORE_SYNC, TRUE);
#endif
	InitVPPara(&tVPInitInfo);
	if(RET_SUCCESS!=vpo_open(g_vpo_dev,&tVPInitInfo))
		ASSERT(0);
#if defined(DUAL_VIDEO_OUTPUT) || defined(DUAL_VIDEO_OUTPUT_USE_VCAP)
	InitVPPara_sd(&tVPInitInfo);
	if(RET_SUCCESS!=vpo_open(g_sd_vpo_dev,&tVPInitInfo))
		ASSERT(0);
#endif

    if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
    {
        if(pre_aspect_ratio == 0xFF)
		{
            logo_info.hdmi_aspect_ratio = TV_16_9;
        }
        else
        {
            if(sys_data_get_aspect_mode() == TV_ASPECT_RATIO_AUTO && logo_info.src_aspect_ratio == DAR_16_9)
            {
                logo_info.hdmi_aspect_ratio = TV_16_9;
            }
            else
            {
                logo_info.hdmi_aspect_ratio = (sys_data_get_aspect_mode() == TV_ASPECT_RATIO_169)? TV_16_9 : TV_4_3;
            }
        }
        
        vpo_ioctl(g_vpo_dev, VPO_IO_SET_LOGO_INFO, (UINT32)&logo_info);
    }
    
#if( defined (SUPPORT_AFD_SCALE)) && ( !defined(_MHEG5_V20_ENABLE_))
        if(g_vpo_dev != NULL)
            vpo_ioctl(g_vpo_dev, VPO_IO_SWAFD_ENABLE, TRUE);
        if(g_sd_vpo_dev != NULL)
            vpo_ioctl(g_sd_vpo_dev, VPO_IO_SWAFD_ENABLE, TRUE);
#endif 

	if(RET_SUCCESS!=dmx_open(g_dmx_dev))
	{
		PRINTF("dmx_open failed!!\n");
		ASSERT(0);
	}

#ifdef NEW_DEMO_FRAME
	if(RET_SUCCESS!=dmx_open(g_dmx_dev2))
	{
		PRINTF("dmx1_open failed!!\n");
		ASSERT(0);
	}
#ifndef _BUILD_OTA_E_    
	if(RET_SUCCESS!=dmx_open(g_dmx_dev3))
	{
		PRINTF("dmx2_open failed!!\n");
		ASSERT(0);
	}
#endif
#endif


//#if((defined(SUPPORT_TWO_TUNER)&&defined(DVR_PVR_SUPPORT)))//dmx 0 will always work in uni buf mode
#if(defined(DVR_PVR_SUPPORT))//for 1 tuner DVR
#if (SYS_CHIP_MODULE != ALI_S3602)
	dmx_io_control(g_dmx_dev, DMX_SWITCH_TO_UNI_BUF, 0);
	dmx_io_control(g_dmx_dev, DMX_CHANGE_THLD, (0<<16)|(16));
#endif
#endif	

#if	(SUBTITLE_ON == 1)
	if(RET_SUCCESS!=sdec_open(g_sdec_dev))
	{
		PRINTF("sdec_open failed!!\n");
		ASSERT(0);
	}
#endif

#if (TTX_ON == 1 )
	if(RET_SUCCESS!=vbi_open(g_vbi_dev))
	{
		PRINTF("vbi_open failed!!\n");
		ASSERT(0);
	}
#endif

#if (CC_ON == 1 ) //vicky20101229 dbg
	if(RET_SUCCESS!=vbi_open(g_vbi_dev2))
	{
		PRINTF("vbi_open failed!!\n");
		ASSERT(0);
	}
#endif
#if	(ISDBT_CC == 1) 
	if(RET_SUCCESS!=sdec_open(g_isdbtcc_dec_dev))
	{
		ASSERT(0);
	}
#endif

#if (defined(HDTV_SUPPORT) && (!defined(HDMI_DISABLE)))
	struct hdmi_device *hdmi_dev;
	hdmi_dev = (struct hdmi_device *)dev_get_by_id(HLD_DEV_TYPE_HDMI, 0);
	if (hdmi_dev == NULL)
	{
		PRINTF("Get device point failed: hdmi_dev=%08x\n", hdmi_dev);
		ASSERT(0);
	}
	else
	{
		if (RET_SUCCESS != hdmi_tx_open(hdmi_dev))
		{
			PRINTF("hdmi_open failed!!\n");
			ASSERT(0);
		}
	}
#endif

#if( defined (SUPPORT_AFD_SCALE))// && ( !defined(_MHEG5_V20_ENABLE_))/* Open AFD @CIPlus version, we don't know why close it at the very beginning */
	{
		struct vp_io_afd_para AFD_Para;
		#ifdef AFD_SW_SUPPORT		 
		AFD_Para.bSwscaleAfd = TRUE;
		#else
		AFD_Para.bSwscaleAfd = FALSE;
		#endif
		AFD_Para.afd_solution = VP_AFD_MINGDIG;
		AFD_Para.protect_mode_enable = TRUE;
        if(g_vpo_dev != NULL)
		    vpo_ioctl(g_vpo_dev, VPO_IO_AFD_CONFIG, (UINT32)&AFD_Para);
        if(g_sd_vpo_dev !=NULL) 
            vpo_ioctl(g_sd_vpo_dev, VPO_IO_AFD_CONFIG, (UINT32)&AFD_Para);
	}
#endif

#ifdef _S3281_
	if(g_vpo_dev != NULL)
	{
		vpo_ioctl(g_vpo_dev, VPO_IO_SET_LAYER_ORDER, MP_GMAS_GMAF_AUXP);
		vpo_ioctl(g_vpo_dev, VPO_IO_PILLBOX_CUT_FLAG, 0);
	}
#endif

	return RET_SUCCESS;
}


static void MHEG5Open(void)
{
#if (defined(_MHEG5_V20_ENABLE_) && !defined(_BUILD_OTA_E_))

	MHEG5ModuleSetup MHEGSetup;

	/*Memory Consumption Parameters*/
	MHEGSetup.memParams.memoryRegionAddr = __MM_MHEG5_BUFFER_ADDR;
	MHEGSetup.memParams.memoryRegionSize = MHEG5_MEMORY_ALLOC_REGION_SIZE;//MHEG5_MEMORY_ALLOC_REGION_SIZE;
	MHEGSetup.memParams.cacheRegionSize	= MHEG5_MEMORY_ALLOC_REGION_SIZE;//MHEG5_MIN_MEMORY_REGION_SIZE;
	MHEGSetup.memParams.numSectionBuffers = 200;//MHEG5_MIN_SECTION_BUFFERS;

	/*parameters for task creation */
	MHEGSetup.taskParams.taskStack = 0x2000;
	MHEGSetup.taskParams.taskTimeQuantum = 10;
	MHEGSetup.taskParams.taskPriority = DEF_PRI;

	/*OSD Window Parameters*/
	MHEGSetup.winParams.winXres = MHEG5_XRES;
	MHEGSetup.winParams.winYres = MHEG5_YRES;
	MHEGSetup.winParams.winVirtualScreen = (UINT32)(__MM_TTX_PB_START_ADDR&0x8ffffff0);
	MHEGSetup.winParams.osdLayer = 1;

	/*manufacture string name*/
	STRCPY(MHEGSetup.manufacturerPlatformString , MHEG_MANUFACTURE_VERSION);

	MHEGSetup.simultaneousSubtitlesAndGraphics = 0;

	MHEG5ApiEngineOpen(&MHEGSetup);
	MHEG5_CreateSpin(SPIN_DATABASE_ACCESS | SPIN_MHEG_MENU);

#endif
}


#ifdef TRUE_COLOR_HD_OSD

extern UINT32 ap_get_osd_scale_param(enum TVSystem eTVMode, INT32 nScreenWidth);

void SetTTxParamater(struct ttx_config_par *pconfig_par)
{    
#ifndef DUAL_ENABLE    
    pconfig_par->osd_get_scale_para = ap_get_osd_scale_param;
#else
    pconfig_par->osd_get_scale_para = NULL;
#endif
	pconfig_par->osd_layer_id = 1;
    #ifdef	SUPPORT_ERASE_UNKOWN_PACKET
	pconfig_par->erase_unknown_packet = TRUE;
    #else
	pconfig_par->erase_unknown_packet = FALSE;
    #endif

    #ifdef	TTX_SUB_PAGE
	pconfig_par->ttx_sub_page = TRUE;
    pconfig_par->ttx_subpage_addr = __MM_TTX_SUB_PAGE_BUF_ADDR;
    #else
	pconfig_par->ttx_sub_page = FALSE;
    pconfig_par->ttx_subpage_addr = 0;
    #endif
    
    #ifdef	USER_FAST_TEXT
	pconfig_par->user_fast_text = TRUE;
    #else
	pconfig_par->user_fast_text = FALSE;
    #endif

    #ifdef NO_TTX_DESCRIPTOR
    pconfig_par->no_ttx_descriptor = TRUE;
    #else
    pconfig_par->no_ttx_descriptor = FALSE;
    #endif

    #if(SYS_SDRAM_SIZE == 2)
    pconfig_par->sys_sdram_size_2m = TRUE;
    #else
    pconfig_par->sys_sdram_size_2m = FALSE;
    #endif

    #ifdef HDTV_SUPPORT
    pconfig_par->hdtv_support_enable = TRUE;
    #else
    pconfig_par->hdtv_support_enable = FALSE;
    #endif

}
void SetSubtitleParamater(struct subt_config_par *pconfig_par)
{
    pconfig_par->sys_sdram_size = SYS_SDRAM_SIZE;
    pconfig_par->max_subt_height = 576;
	pconfig_par->osd_layer_id = 1;  
    
    #ifdef CC_BY_VBI
    pconfig_par->cc_by_vbi = TRUE;
    #else
    pconfig_par->cc_by_vbi = FALSE;
    #endif

    #ifdef CC_BY_OSD
    pconfig_par->cc_by_osd = TRUE;
    #else
    pconfig_par->cc_by_osd = FALSE;
    #endif

    #ifdef OSD_BLOCKLINK_SUPPORT
    pconfig_par->osd_blocklink_enable = TRUE;
    pconfig_par->g_ps_buf_addr = 0;
	pconfig_par->g_ps_buf_len = 0;
    #else
    pconfig_par->osd_blocklink_enable = FALSE;
    pconfig_par->g_ps_buf_addr = (UINT8*)__MM_SUB_PB_START_ADDR;
	pconfig_par->g_ps_buf_len = __MM_SUB_PB_LEN;
    #endif

    #ifdef SPEED_UP_SUBT
    pconfig_par->speed_up_subt_enable = TRUE;
    #else
    pconfig_par->speed_up_subt_enable = FALSE;
    #endif

    #ifdef HD_SUBTITLE_SUPPORT
    pconfig_par->hd_subtitle_support = TRUE;
    pconfig_par->osd_get_scale_para = ap_get_osd_scale_param; 
    #else
    pconfig_par->hd_subtitle_support = FALSE;
    pconfig_par->osd_get_scale_para = NULL;
    #endif
	pconfig_par->osd_buf=__MM_OSD_BK_ADDR2;
	pconfig_par->osd_buf_length=__MM_OSD2_LEN;
}
#endif

//extern INT32 api_diseqc_set_22k_envelop(struct nim_device *lib_diseqc_nim_dev, UINT8 mode);
#ifdef NEW_DEMO_FRAME
void regist_device_to_manage()
{
	struct nim_config nim_config_info;
	MEMSET(&nim_config_info, 0, sizeof(nim_config_info));
/*	if(g_nim_dev!=NULL)
	{
   	    dev_register_device((void *)g_nim_dev, HLD_DEV_TYPE_NIM, 0, board_get_frontend_type(0));
	} 
	if(g_nim_dev2!=NULL)
	{
    	dev_register_device((void *)g_nim_dev2, HLD_DEV_TYPE_NIM, 1, board_get_frontend_type(1));
	} */
	if(g_dmx_dev != NULL)
	{
		dev_register_device((void *)g_dmx_dev, HLD_DEV_TYPE_DMX, 0, 0);
	}
	if(g_dmx_dev2 != NULL)
	{
		dev_register_device((void *)g_dmx_dev2, HLD_DEV_TYPE_DMX, 1, 0);
	}
	if(g_dmx_dev3 != NULL)
	{
		dev_register_device((void *)g_dmx_dev3, HLD_DEV_TYPE_DMX, 2, 0);
	}
	if(g_decv_dev != NULL)
	{
		dev_register_device((void *)g_decv_dev, HLD_DEV_TYPE_DMX, 0, 0);
	}
}
#endif


#ifdef MULTI_CAS
#if (CAS_TYPE == CAS_ABEL)  /* SUPPORT_CAS_A */
#define MAX_STB_ID_SIZE 30 
//RSA Key 516byte + key reference 4byte + STB ID (MAX  30byte) = 550byte

UINT16 load_stb_identify(UINT8 *stb_id, UINT16 id_len)
{
	UINT8 buf[MAX_STB_ID_SIZE];
	UINT32 id = 0; //bootloader ID
	UINT8 i=0;
	unsigned long bl_offset;
	
	MEMSET(stb_id, 0, id_len);
	
	//sto_get_data( (struct sto_device *)dev_get_by_id(HLD_DEV_TYPE_STO, 0), buf,
	//					(UINT32)sto_chunk_goto(&id,0xFFFFFFFF,1) + CHUNK_HEADER_SIZE+520, MAX_STB_ID_SIZE);

	bl_offset = sto_fetch_long(0 + CHUNK_OFFSET);
	sto_get_data((struct sto_device *)dev_get_by_id(HLD_DEV_TYPE_STO, 0), (UINT8 *)buf, bl_offset - MAX_STB_ID_SIZE, MAX_STB_ID_SIZE);


	while((buf[i] !=0) && (i<MAX_STB_ID_SIZE))
	{
		if(i<id_len-1)
			stb_id[i] = buf[i];
		i++;
	}
	
	return i;
}

static void AbelConfig( )
{

	UINT8 	*link_encytption_keys;
	UINT8 	Key1[8] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
	UINT8 	Key2[8] = {0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01};
	UINT8 	Key3[8] = {0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23};
	UINT8	Plaintext[8];
	UINT16	 i;
	UINT32 id =0; //bootloader ID
	unsigned long bl_offset;
	
	link_encytption_keys = (UINT8 *)MALLOC(sizeof(UINT8)*520);
	
	//sto_get_data( (struct sto_device *)dev_get_by_id(HLD_DEV_TYPE_STO, 0), link_encytption_keys,
						//(UINT32)sto_chunk_goto(&id,0xFFFFFFFF,1) + CHUNK_HEADER_SIZE, 520);

	bl_offset = sto_fetch_long(0 + CHUNK_OFFSET);
	sto_get_data((struct sto_device *)dev_get_by_id(HLD_DEV_TYPE_STO, 0), (UINT8 *)link_encytption_keys, bl_offset - 550, 520);
		
	 for(i=0; i<520; i++)
	 {
	 	if(link_encytption_keys[i] != 0xFF)
	 	{
	 		abel_key_is_existed();
	 		break;
	 	}
	 }

	 for(i=0; i<520; i+=8)
	{
		TripleDES_Decryption(link_encytption_keys+i, Plaintext, Key1, Key2, Key3);       
		memcpy(link_encytption_keys+i, Plaintext, 8);            
	 } 

	 set_private_key((R_RSA_PUBLIC_KEY*)link_encytption_keys);
	 set_link_encryption_key_ref(&link_encytption_keys[516]);
	 	
	 free(link_encytption_keys);
	//set_pairing_function_onoff(FALSE);
	 api_set_inbox_chunk_id(0x08F70100);

}
#endif
#endif


void pmu_notify(UINT32 param)
{
 #ifdef PMU_ENABLE    
 //   pmu_m36_en();
  if((ALI_S3811==sys_ic_get_chip_id()) && (sys_ic_get_rev_id() >= IC_REV_1))
   {
         ap_send_msg(CTRL_MSG_SUBTYPE_KEY_UI, V_KEY_POWER, TRUE);
		#ifdef AUTO_OTA
		extern BOOL m_ForFakeStandby;
		if(m_ForFakeStandby )
		 ota_power_flag=TRUE;
		#endif
  	}
    if(((ALI_C3701==sys_ic_get_chip_id()) && (sys_ic_get_rev_id() >= IC_REV_1))||(ALI_S3503==sys_ic_get_chip_id()||(ALI_S3821==sys_ic_get_chip_id())))
   {
         ap_send_msg(CTRL_MSG_SUBTYPE_KEY_UI, V_KEY_POWER, TRUE);
		#ifdef AUTO_OTA
		extern BOOL m_ForFakeStandby;
		if(m_ForFakeStandby )
		 ota_power_flag=TRUE;
		#endif
  	}
    if((ALI_S3811==sys_ic_get_chip_id()) && (sys_ic_get_rev_id() == IC_REV_0))
  	{
		ap_send_msg(CTRL_MSG_SUBTYPE_KEY_UI, V_KEY_POWER, TRUE);
		#ifdef AUTO_OTA
		extern BOOL m_ForFakeStandby;
		if(m_ForFakeStandby )
		 ota_power_flag=TRUE;
		#endif
    }
 #endif 
    return ;
}
void ddr_256m_supprot(void)
{
	 *(volatile UINT32 *)(0xb8000220) |= (0x01<<24);//bit24  set 1, after  192M  address for DRAM
     *(volatile UINT32 *)(0xb8000110) |= 0x01;//bit0  set 1,Flash memory for spi flash, default for BootRom 
}
#if (AOV_YJ_POWER_LED_MODE2_ENABLE == SYS_FUNC_ON)
void LED_yellow_on()
{
//Gavim@YJ_POWER_LED
UINT32 data;
	
	// Set pin115 enabled
	*((unsigned long *)0xb8000440) |= 0x3;
		
	data = *((unsigned long *)0xb8000440);
	libc_printf("Chip Reg[440]=   %lx\n",data);
			
	HAL_GPIO_BIT_DIR_SET(128, HAL_GPIO_O_DIR);
	HAL_GPIO_BIT_DIR_SET(129, HAL_GPIO_O_DIR);
	
	//HAL_GPIO_BIT_SET(134, 0);	//Pin115
	HAL_GPIO_BIT_SET(128, 0);	
	HAL_GPIO_BIT_SET(129, 1);	
	//------------------	
}
#endif

void system_hw_init(BoardCfg* cfg)
{
    set_board_cfg(cfg);
    
    //init chip 
    global_chip_set(chip_create());
    chip_init(&(cfg->chip_param));
    
    //config gpio
    chip_gpio_pin_init_ext(cfg->all_gpio_array, cfg->all_gpio_count);

	//for 256M DDR
	#ifdef DDR_256M_SUPPORT
		ddr_256m_supprot();
 	#endif

    if((NULL != cfg->front_end_cfg[0] && cfg->front_end_cfg[0]->front_end_type == FRONTEND_TYPE_S)
        || (NULL != cfg->front_end_cfg[1] && cfg->front_end_cfg[1]->front_end_type == FRONTEND_TYPE_S))
    {
        // power off 1000ms to work around IC bug
        chip_gpio_set(cfg->sys_power, 0);
	    osal_task_sleep(1000);
    }

    //config pinmux
    chip_pin_mux_set_ext(cfg->pin_mux_array, cfg->pin_mux_count); 

    //for M3823 Network LED GPIO15/2 init
    if(SYS_MAIN_BOARD == BOARD_DB_M3823_02V01 || SYS_MAIN_BOARD == BOARD_DB_M3823_01V01)
    {
        HAL_GPIO_BIT_SET(15,1);
        HAL_GPIO_BIT_SET(2,1);
    }
    
    //power on
    board_power(TRUE);

#if (AOV_YJ_POWER_LED_MODE2_ENABLE == SYS_FUNC_ON)    
		// Gavim@LED_20150226
		LED_yellow_on();
#endif

#ifdef DUAL_ENABLE
	hld_dev_see_init(__MM_SEE_DBG_MEM_ADDR);
#endif

    //sci
	UINT32 port_disbale = 0;
#ifdef _CAS9_CA_ENABLE_
#ifndef _BUILD_OTA_E_
	otp_init(NULL);
	otp_read(0x3*4, &port_disbale, 4);
	if(port_disbale&(1<<12))
		port_disbale = 1;
	else
		port_disbale = 0;
#endif
#endif
	if(port_disbale == 0)
	{
#if 1//ndef DISABLE_PRINTF
    board_sci_init();
#endif
	}


#ifndef _BUILD_OTA_E_
	// warning, please don't remove version information
	// it's very helpfull for us to debug/trace issue.
	#ifdef SFU_TEST_SUPPORT
	//SciEcho("MC: APP  init ok\r\n");
	//SciEcho(get_sdk_ver());
	//SciEcho("\r\n");
	//SciEcho(get_core_ver());
	//SciEcho("\r\n");
	//SciEcho(get_app_ver());
	//SciEcho("\r\n");
	#else
	FIXED_PRINTF("MC: APP  init ok\r\n");
	FIXED_PRINTF("%s\r\n", get_sdk_ver());
	FIXED_PRINTF("%s\r\n", get_core_ver());
	FIXED_PRINTF("%s\r\n", get_app_ver());
	#ifdef SUPPORT_CAS_A	
	FIXED_PRINTF("%s\r\n", get_abel_ver());
	#endif
	#endif
#endif    

	UINT64 nec_ir_key_first = 0x60df708f;
#ifdef PMU_ENABLE    
    /* pmu sw/hw init */
#if (AOV_RC_MODEL == ARC010 || AOV_RC_MODEL == ARC019 || AOV_RC_MODEL == ARC020)//ChengYu@20130916, set AOV IR power key keycode to PMU
	nec_ir_key_first = 0xc066b847;
#endif
//Gavim@yj_remote
#if (AOV_RC_MODEL ==  YAOJIN01) //Martin@Yj01_remote
	nec_ir_key_first = 0x807F807F;
#endif
#if (AOV_RC_MODEL ==  YAOJIN02) //Martin@Yj02_remote
	nec_ir_key_first = 0x00ff9a65;
#endif
	unsigned char ir_type  = 0;
	unsigned char pmu_pan_type = 0x0;
    pmu_m36_attach(pmu_notify , NULL);
	UINT64 nec_ir_key_second = 0;
	/*
	PAN_TYPE_CH455 = 0
	PAN_TYPE_FD650K =1
	*/
	pmu_panel_type(pmu_pan_type,0);
    pmu_m36_ir_init();
	//PMU_Key_Transfrom(nec_ir_key,ir_type);
    PMU_Key_Transfrom_extend(nec_ir_key_first,ir_type,nec_ir_key_second,ir_type,NULL);
	rtc_s3811_set_tick_msk(0);           //step1
#endif
    if((ALI_C3701==sys_ic_get_chip_id()) ||(ALI_S3503==sys_ic_get_chip_id())||(ALI_S3821==sys_ic_get_chip_id()))
   	{
   	   #ifdef RTC_TIME_SUPPORT
          south_rtc_init(0);
	   #endif
    }
   if((ALI_S3811==sys_ic_get_chip_id()) && (sys_ic_get_rev_id() >= IC_REV_1))
   	{
   	  #ifndef PMU_ENABLE
      rtc_s3811_set_tick_msk(0);          
      #endif
   	}
    //i2c
    board_i2c_init();

    //scart
    if((NULL != cfg->scart_attach) && (NULL != cfg->scart_param))
    {
        cfg->scart_attach(cfg->scart_param);
        g_scart_dev = (struct scart_device *)dev_get_by_id(HLD_DEV_TYPE_SCART, 0);
    }

    //front panel
    if(NULL != cfg->pan_attach && NULL != cfg->pan_config)
    {
        cfg->pan_attach(cfg->pan_config);        
        g_pan_dev = (struct pan_device *)dev_get_by_id(HLD_DEV_TYPE_PAN, 0);
        if(NULL != cfg->pan_i2c_id_set)
            cfg->pan_i2c_id_set(g_pan_dev, cfg->pan_i2c_id);     
 	    pan_open(g_pan_dev);
	    pan_display(g_pan_dev, " ON ", 4);//ChengYu@20140212, LED pannel
    }


#if (AOV_YJ_POWER_LED_MODE2_ENABLE == SYS_FUNC_ON) 
		// Gavim@LED_20150226
		LED_yellow_on();
#endif
		
    //flash
    if(cfg->flash_type == 1)
        sto_local_flash_attach(NULL);
    else
        sto_local_sflash_attach(NULL);
    
	g_sto_dev = (struct sto_device *)dev_get_by_type(NULL, HLD_DEV_TYPE_STO);
	sto_open(g_sto_dev);
	sto_chunk_init(0, g_sto_dev->totol_size);	//sto_eeprom_init();

    //rfm
    if(NULL != cfg->rfm_attach)
    {
        cfg->rfm_attach();
    	g_rfm_dev = (struct rfm_device*)dev_get_by_id(HLD_DEV_TYPE_RFM, 0);
        if(NULL != g_rfm_dev)
        {
            g_rfm_dev->i2c_type_id_cfg = 1;
    	    g_rfm_dev->i2c_type_id = cfg->rfm_i2c_id;
        }
    	//rfm_open(g_rfm_dev);        
    }
    
    //frontend
	board_frontend_init();
    //advance init
    g_nim_dev = dev_get_by_id(HLD_DEV_TYPE_NIM, 0);
    g_nim_dev2 = dev_get_by_id(HLD_DEV_TYPE_NIM, 1);
    if(NULL == g_nim_dev && NULL == g_nim_dev2)
    {
        ASSERT(0);
    }
    else if(NULL == g_nim_dev2)
        cfg->adv_cfg_para.front_end_num = 1;
    else
        cfg->adv_cfg_para.front_end_num = 2;

#ifdef NEW_DEMO_FRAME  /* Frank.T */
   	if(g_nim_dev!=NULL)
	{
   	    dev_register_device((void *)g_nim_dev, HLD_DEV_TYPE_NIM, 0, board_get_frontend_type(0));
	}
	if(g_nim_dev2!=NULL)
	{
    	dev_register_device((void *)g_nim_dev2, HLD_DEV_TYPE_NIM, 1, board_get_frontend_type(1));
	}   	
#endif
		
#ifdef MULTI_CAS       
    cfg->adv_cfg_para.class_select = board_class_select;
#endif
#ifdef FPGA_TEST
    cfg->adv_cfg_para.scart_aspect_change = NULL;
#else
    cfg->adv_cfg_para.scart_aspect_change = api_scart_aspect_callback;
#endif

    if(m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
    {
       cfg->adv_cfg_para.vpo_active = TRUE;
    }
    else
    {
       cfg->adv_cfg_para.vpo_active = FALSE; 
    }
    
    board_advance_init(&(cfg->adv_cfg_para));
    g_ge_dev = dev_get_by_type(NULL,HLD_DEV_TYPE_GE);

#ifdef USB_MP_SUPPORT
	#ifdef ALI_SDK_API_ENABLE
		//deca_ext_dec_enable((struct deca_device*)dev_get_by_id(HLD_DEV_TYPE_DECA, 0));
	#endif
#ifdef PVR_FS_ZH    
    init_file_system();
#endif
#endif
//modify bomur 2011 09 17       
//#ifdef NETWORK_SUPPORT
   //network_attach();
//#endif
#if ((defined(NETWORK_SUPPORT)) && (!defined(MAC_TEST)))
	network_attach();
#endif
//modify end

#ifdef MULTI_CAS
#if (CAS_TYPE == CAS_ABEL)  /* SUPPORT_CAS_A */
	AbelConfig();
#endif
#endif
}


static INT32 nim_s3501_reset_tuner(UINT32 err)
{
	UINT8 tuner_id = err>>16;

	if(tuner_id)
		tuner_id--;

    if(tuner_id)
        board_frontend_reset(1);
    else if(board_get_frontend_type(0) == FRONTEND_TYPE_S)
        board_frontend_reset(0);
    else
        board_frontend_reset(1);

#ifndef FPGA_TEST
#ifdef PSI_MONITOR_SUPPORT
    if (err) // I2C read/write error, replay current channel by UI
        ap_pid_change(TRUE);
#endif
#endif
    return 0;
}

static void front_end_re_open(struct nim_device* nim_dev, UINT8 frontend_id)
{
    int reset_count = 0;
    if(NULL == nim_dev)
        return;
    do
    {
        board_frontend_reset(frontend_id);
        reset_count++;
        if(SUCCESS == nim_open(nim_dev))
            break;
        if (reset_count >= 10)
        {
            libc_printf("ERROR: reset nim failed!!!\n");
            break;
        }
        osal_task_sleep(100);
    } while (1);        
}

static void front_end_open()
{
    g_nim_dev = dev_get_by_id(HLD_DEV_TYPE_NIM, 0);    

    if(NULL != g_nim_dev)
    {
       if(SUCCESS != nim_open(g_nim_dev))
       {
            front_end_re_open(g_nim_dev, 0);  
       }    
    //  api_diseqc_set_22k_envelop(g_nim_dev,1);  //only for envelop 22k signals,LNBP12 chipset
    }
    else
    {
        ASSERT(0);
    }
    
//#ifdef  _CAS7_CA_ENABLE_
#if 0
    nim_io_control(g_nim_dev, NIM_DRIVER_SET_RESET_CALLBACK, (UINT32)nim_s3501_reset_tuner);
    g_tuner_num = 1;
#else
    g_nim_dev2 = dev_get_by_id(HLD_DEV_TYPE_NIM, 1);	

    if(NULL != g_nim_dev2)
    {
        if(SUCCESS != nim_open(g_nim_dev2))
        {
             front_end_re_open(g_nim_dev2, 1);  
        }
    }     
    
   if(FRONTEND_TYPE_S == board_get_frontend_type(0) || FRONTEND_TYPE_S == board_get_frontend_type(1))
        	nim_io_control(g_nim_dev, NIM_DRIVER_SET_RESET_CALLBACK, (UINT32)nim_s3501_reset_tuner);
   
    if(NULL != g_nim_dev2)
        g_tuner_num = 2;
    else
        g_tuner_num = 1;
#endif

#ifdef DVBC_MODE_CHANGE
   struct DEMOD_CONFIG_ADVANCED demod_config;					 
   if(NULL != g_nim_dev)
   {	
	  SYSTEM_DATA* sys_data;
	  sys_data = sys_data_get();
	  
   	  front_end_c_get_QAM_config(sys_data->dvbc_mode,NIM_SAMPLE_CLK_27M,&demod_config);
	  nim_ioctl_ext(g_nim_dev, NIM_DRIVER_SET_NIM_MODE, (void *)&demod_config);
	  
   }
#endif
	
}


#ifdef SUPPORT_CAS9
#ifndef _RD_DEBUG_
// This function is defined in upgrade_serial.c --->
extern RET_CODE generate_stbinfo_hmac(UINT8 *input, const UINT32 len, UINT8 *output);
// < --- end

static RET_CODE check_stbinfo_hmac(UINT8 *addr, const UINT32 len)
{
	UINT8 hmac_output[HMAC_OUT_LENGTH] = {0};
	UINT8 *hmac_addr = NULL;
	UINT32 data_len = 0;
	RET_CODE ret = RET_FAILURE;

	data_len = len - HMAC_OUT_LENGTH;
	hmac_addr = addr + data_len;
	ret = generate_stbinfo_hmac(addr, data_len, hmac_output);
	if (RET_SUCCESS != ret)
    {
		return ret;
	}

	if (0 == MEMCMP(hmac_addr, hmac_output, HMAC_OUT_LENGTH))
	{
		return RET_SUCCESS;
	}
	else
	{
		return RET_FAILURE;
	}
}

BOOL verify_stbinfo_sig()
{
    RET_CODE ret = RET_SUCCESS;
	UINT32 chunk_hdr = 0, chunk_data = 0,chunk_data_len = 0;
    UINT32 stb_chunk_id = 0x20DF0100;
    struct sto_device *test_flash_dev = NULL;
    UINT32 data_base = 0;
    
    test_flash_dev = (struct sto_device *)dev_get_by_type(NULL, HLD_DEV_TYPE_STO);        
    chunk_hdr = (UINT32)sto_chunk_goto(&stb_chunk_id, 0xFFFF0000, 1); 
    if ((ERR_PARA == chunk_hdr) || (ERR_FAILUE == chunk_hdr) || (NULL == test_flash_dev))
    {
        return RET_FAILURE;
    }

	chunk_data = chunk_hdr + CHUNK_HEADER_SIZE;
	chunk_data_len = sto_fetch_long(chunk_hdr + CHUNK_LENGTH) - CHUNK_HEADER_SIZE + CHUNK_NAME;    

    data_base = MALLOC(chunk_data_len + 0XF);
    if (NULL == data_base)
    {
        return RET_FAILURE;
    }

    ret = sto_get_data(test_flash_dev, data_base, chunk_data, chunk_data_len);
    if (chunk_data_len != ret)
    {
        return RET_FAILURE;
    }

	// check by HMAC mode
	if (RET_SUCCESS==check_stbinfo_hmac((UINT8 *)data_base, chunk_data_len))
	{
		ret = RET_SUCCESS;
	}
	else // check by signature mode
	{
	    if (0 == Test_RSA_Ram((UINT32)data_base, chunk_data_len))
	    {
	        //libc_printf("success \n");
	        ret = RET_SUCCESS;
	    }
	    else
	    {
	        //libc_printf("fail \n");
	        ret = RET_FAILURE;
	        hw_watchdog_reboot();
	        while(1);
	    }
	}
    FREE(data_base);
    
    return ret;
}
#endif
#endif

void AppInit()
{
	INT32 ret;
	UINT32 chunk_id,db_len,db_addr;
	SYSTEM_DATA* sys_data;
    UINT32 scart_out;
    struct TRANS_VDEC_INFO vdec_info;
    UINT32 show_logo_flag = 0;
    
    MEMSET(&vdec_info, 0, sizeof(vdec_info));
    
#ifdef _RD_DEBUG_
    if(ALI_S3503==sys_ic_get_chip_id())
        ali_debug_enable();
#endif

    get_sysinfo_from_bl(TRANS_VDEC_TYPE, &vdec_info, sizeof(vdec_info));
        
    logo_info.src_aspect_ratio = vdec_info.aspect_ratio;
    logo_info.pic_height = vdec_info.pic_height;
    logo_info.pic_width = vdec_info.pic_width;
    show_logo_flag = vdec_info.resv[0];

    if((show_logo_flag == 1) && ((*(unsigned long *)0xb8006000) & 1) && sys_ic_get_chip_id() == ALI_S3503)   
    { 
        m_boot_vpo_active = 1;               
    }    
    else   
    {        
        m_boot_vpo_active = 0;   
    }
    
    system_hw_init(get_board_config());
    
	
#ifdef _IDL_EXT_ENABLE
    //dsc_api_attach();
    idl_init();
#endif
#ifndef _BUILD_OTA_E_
	sys_data = sys_data_get();
	chunk_id = 0x04FB0100;
	api_get_chunk_add_len(chunk_id, &db_addr, &db_len);
#ifdef SUPPORT_FRANCE_HD
	db_len = db_len - (2*64*1024);//last sector for temp info
#else
#ifdef BACKUP_TEMP_INFO
	db_len = db_len - (64*1024)*2;//last sector for temp info //alan modify
#else
	db_len = db_len - (64*1024);//last sector for temp info //alan modify
#endif
#endif
	init_tmp_info(db_addr + db_len, 64*1024);
#ifdef SUPPORT_FRANCE_HD
	init_nit_info(db_addr + db_len+64*1024, 64*1024);
#endif
	sys_data_factroy_init();
	ret = load_tmp_data((UINT8*)sys_data,sizeof(SYSTEM_DATA));
    scart_out = sys_data_get_scart_out();

    if(ret == SUCCESS && m_boot_vpo_active == 1 && sys_ic_get_chip_id() == ALI_S3503)
    {
    	switch(sys_data->avset.tv_mode)
    	{
        	case TV_MODE_PAL:			
                pre_tv_mode = PAL;
                break;
        	case TV_MODE_PAL_N:	
                pre_tv_mode = PAL_N;
                break;
        	case TV_MODE_NTSC358:
                pre_tv_mode = NTSC;
                break;
        	case TV_MODE_PAL_M:
                pre_tv_mode = PAL_M;
                break;
        	case TV_MODE_NTSC443:
                pre_tv_mode = NTSC_443;
                break;
        	case TV_MODE_SECAM:
                pre_tv_mode = SECAM;
                break;		
        	case TV_MODE_480P:			
                pre_tv_mode = NTSC;
                break;
        	case TV_MODE_576P:			
                pre_tv_mode = PAL;
                break;
        	case TV_MODE_720P_50:	
                pre_tv_mode = LINE_720_25;
                break;
        	case TV_MODE_720P_60:		
                pre_tv_mode = LINE_720_30;
                break;
        	case TV_MODE_1080I_25:		
                pre_tv_mode = LINE_1080_25;
                break;
        	case TV_MODE_1080I_30:		
                pre_tv_mode = LINE_1080_30;
                break;
        	case TV_MODE_1080P_25:
                pre_tv_mode = LINE_1080_25;
                break;
        	case TV_MODE_1080P_30:
                pre_tv_mode = LINE_1080_30;
                break;
        	case TV_MODE_1080P_24:		
                pre_tv_mode = LINE_1080_24;
                break;
        	case TV_MODE_1080P_50:		
                pre_tv_mode = LINE_1080_50;
                break;
        	case TV_MODE_1080P_60:
                pre_tv_mode = LINE_1080_60;
                break;
            default:
        		pre_tv_mode = LINE_1080_25;
                break;	
	    }
    }
    else
    {
    	if(ret == SUCCESS)
    	{
    		switch(sys_data->avset.tv_mode)
    		{
    		case TV_MODE_PAL:
    			pre_tv_mode = PAL;
    			break;
    		case TV_MODE_PAL_M:
    			pre_tv_mode = PAL_M;
    			break;
    		case TV_MODE_PAL_N:
    			pre_tv_mode = PAL_N;
    			break;
    		case TV_MODE_NTSC358:
    			pre_tv_mode = NTSC; 
    			break;

    		default:
    			pre_tv_mode = LINE_720_30;//PAL;
    			break;
    		}
    	}
    }
  
#endif

	MHEG5Open();

#ifdef HDCP_FROM_CE
	ce_generate_hdcp();
#endif

	avInit();
	avStart();
    
	if(ret == SUCCESS)
	{
#ifdef POS_SCART_VCR_DETECT
		if(api_Scart_VCR_Detect())
		{
			//api_Scart_RGB_OnOff(0);
			api_Scart_OutPut_Switch(0);
		}
		else
		{
			api_Scart_RGB_OnOff((scart_out == SCART_RGB) ? 1 : 0);
#ifdef VDAC_USE_SVIDEO_TYPE
			api_Svideo_OnOff((scart_out == SCART_SVIDEO) ? 1 : 0);
#endif
			api_Scart_OutPut_Switch(1);
		}
#else    
		api_Scart_RGB_OnOff( (scart_out == SCART_RGB) ? 1 : 0);
#ifdef VDAC_USE_SVIDEO_TYPE
		api_Svideo_OnOff((scart_out == SCART_SVIDEO) ? 1 : 0);
#endif
#endif
    }

//set dsc priority for s3602f
#ifdef S3602F_AES_PATCH
	aes_set_prior();
#endif


#if((defined(DSC_SUPPORT) ||(defined(HDCP2_SUPPORT)) ||defined(MULTI_CAS)) && defined(M36F_CHIP_MODE))

    dsc_api_attach();
#endif

#if((defined SUPPORT_CAS9 || defined(MULTI_CAS)) && defined(M36F_CHIP_MODE) || defined(_VMX_STD_3281_) || defined(SUPPORT_VMX_STD) )
		ret = -1;
		UINT32 para = 0;
		struct dec_parse_param param;
		pDSC_DEV  pDscDev= NULL;
		pCSA_DEV  pCsaDev= NULL;
	
		//dsc_api_attach();
	
		if (pDscDev == NULL)
		{
			pDscDev = (pDSC_DEV)dev_get_by_id(HLD_DEV_TYPE_DSC, 0);
			if(pDscDev==NULL)
			{	 
				PRINTF("%s - get DSC Dev failed!\n",__FUNCTION__);
				ASSERT(0);
			}
		}
		if (pCsaDev == NULL)
		{
			ret = dsc_ioctl(pDscDev, IO_DSC_GET_CSA_HANDLE, (UINT32)&para);
			if(ret!=SUCCESS)
			{
				PRINTF("%s - get CSA Dev failed!\n",__FUNCTION__);
				ASSERT(0);
			}
			pCsaDev = (pCSA_DEV)para;
		}
		
		param.dec_dev = pCsaDev;
		param.type= CSA; 
		dmx_io_control(g_dmx_dev, IO_SET_DEC_HANDLE, (UINT32)&param);
		dmx_io_control(g_dmx_dev, IO_SET_DEC_STATUS, (UINT32)1);
#endif

#if (defined(CAS7_PVR_SUPPORT) || defined(VMX_PVR_STD_SUPPORT)) 
	dsc_set_stream_id_used(0);
	dsc_set_stream_id_used(1);
#endif
	/* open  RF module  */
    if(NULL != g_rfm_dev)
	    rfm_open(g_rfm_dev);

    //open frontend 
    front_end_open();
#if defined(SUPPORT_VMX_STD) || defined(SUPPORT_VMX)
	g_smc_dev = (struct smc_device *)dev_get_by_id(HLD_DEV_TYPE_SMC, 0);  
#endif

#if defined(HDTV_SUPPORT) && (!defined(HDMI_DISABLE))
	if(api_hdmi_register()!=SUCCESS)
		PRINTF("api_hdmi_register Init failed!\n");
	
	if (vpo_ioctl(g_vpo_dev, VPO_IO_REG_CB_HDMI, (UINT32)set_video_info_to_hdmi) != RET_SUCCESS)
		PRINTF("register video callback of HDMI failed!\n");
	
	if (snd_io_control(g_snd_dev, SND_REG_HDMI_CB, (UINT32)set_audio_info_to_hdmi) != RET_SUCCESS)
		PRINTF("register sound callback of HDMI failed!\n");
#ifdef _BUILD_OTA_E_
	api_set_hdmi_res(HDMI_RES_720P_60);
#endif
	struct hdmi_device *hdmi_dev = (struct hdmi_device *)dev_get_by_type(NULL,HLD_DEV_TYPE_HDMI);	
	hdmi_dev->io_control(hdmi_dev,HDMI_CMD_REG_CALLBACK, HDMI_CB_EDID_READY, (UINT32)hdmi_edid_ready_callback);	
    hdmi_dev->io_control(hdmi_dev,HDMI_CMD_REG_CALLBACK, HDMI_CB_HOT_PLUG_OUT, (UINT32)hdmi_hot_plug_out_callback);

	/* enable to configure hdmi audio cap reset function in snd driver */   
	snd_io_control(g_snd_dev, SND_HDMI_ENABLE, TRUE);
#else	
	/* disable to configure hdmi audio cap reset function in snd driver */ 
	snd_io_control(g_snd_dev, SND_HDMI_ENABLE, FALSE);
#endif

#ifndef HDTV_SUPPORT
	api_show_bootup_logo();
#endif


#ifdef NEW_DEMO_FRAME
	regist_device_to_manage();  //Frank.T

	struct pub_module_config config;

	MEMSET(&config, 0, sizeof(config));
    	config.dm_enable = FALSE;
	if(libpub_init(&config) != RET_SUCCESS)
		PRINTF("libpub_init Init failed\n");
#else
	if(libpub27_init()!=RET_SUCCESS)
	PRINTF("libpub27_init Init failed\n");
#endif

#if	(TTX_ON == 1)
#ifdef TRUE_COLOR_HD_OSD
    struct ttx_config_par ttx_config_par; 
    memset(&ttx_config_par,0x00,sizeof(ttx_config_par));
    SetTTxParamater(&ttx_config_par);
    TTXEng_Attach(&ttx_config_par);    
   // TTxOSD_SetSize(576,520);
#else
	TTXEng_Init();
#endif
    TTXEng_set_g0_set();
//modify for TTX and EPG share buffer 2011 10 10
#ifndef TTX_EPG_SHARE_MEM	
	ttx_enable(TRUE);
#endif
#endif
#if (SUBTITLE_ON == 1)
#ifdef TRUE_COLOR_HD_OSD
    struct subt_config_par subt_config_par;
    memset(&subt_config_par,0x00,sizeof(subt_config_par));
    SetSubtitleParamater(&subt_config_par);
    lib_subt_attach(&subt_config_par);
#endif
    
	subt_enable(TRUE);
#endif
#if(CC_ON==1)	//vick20110210
	#ifdef CC_BY_OSD
	set_cc(sys_data_get_cc_control());
	set_dtv_cc_service(sys_data_get_dtvcc_service());
//	libc_printf("Root.c: CC(%d),CS(%d)",sys_data_get_cc_control(),sys_data_get_dtvcc_service());
	#endif
#endif

#if (ISDBT_CC == 1)
	struct isdbtcc_config_par cc_config_par;
	memset(&cc_config_par,0x00,sizeof(cc_config_par));
	cc_config_par.g_buf_addr=(UINT8*)__MM_ISDBTCC_PB_START_ADDR;
	cc_config_par.g_buf_len=__MM_ISDBTCC_PB_LEN;
	cc_config_par.max_isdbtcc_height=540;	
	cc_config_par.isdbtcc_height=540;
	cc_config_par.isdbtcc_width=960;
	cc_config_par.isdbtcc_hor_offset=0;
	cc_config_par.isdbtcc_ver_offset=0;
	cc_config_par.isdbtcc_osd_layer_id=1;
	lib_isdbtcc_attach(&cc_config_par);
	isdbtcc_enable(TRUE);
#endif
#if defined(FPGA_TEST) //|| (SYS_MAIN_BOARD == BOARD_SB_S3602F_QFP_01V01)
    // disable ota upgrade
#else
	ota_init();//useless if secondloader is on function
//**********************//add by Iris for Auto OTA
#ifdef AUTO_OTA_SAME_VERSION_CHECK
#ifndef _BUILD_OTA_E_    
    ota_config_ex(SYS_OUI, SYS_HW_MODEL, SYS_HW_VERSION, SYS_SW_MODEL, SYS_SW_VERSION, DIFFERENT_SOFTWARE_VERSION);
#else
    ota_config(SYS_OUI, SYS_HW_MODEL, SYS_HW_VERSION, SYS_SW_MODEL);
#endif
#endif
#if !defined(_BUILD_OTA_E_) && defined(AUTO_OTA)
	si_set_ota_config(SYS_HW_MODEL,SYS_HW_VERSION,SYS_OUI,SYS_SW_MODEL,SYS_SW_VERSION);
#endif
//**********************//end
#endif

#if (defined MULTI_CAS && (!defined SUPPORT_CAS9))&&(!defined SUPPORT_CAS7)&&(!defined SUPPORT_DVTCA)
	void ap_mcas_display(mcas_disp_type_t type, UINT32 param);
	api_mcas_register(ap_mcas_display);
#endif

#if defined SUPPORT_DVTCA
	cas_init();
#endif

#ifdef CI_SUPPORT
	void ap_parse_ci_msg(int slot, enum api_ci_msg_type type);

	if (api_ci_register(NULL,ap_parse_ci_msg) != SUCCESS)
	{
		PRINTF("Register CI stack fail\n");
	}

#ifdef CI_PLUS_SUPPORT
	void ap_ci_camup_progress_callback(int percent);
    void ap_ci_playch_callback(UINT32 prog_id);
	api_ci_register_callback(NULL, ap_ci_camup_progress_callback);
    api_ci_register_playch_callback(NULL, ap_ci_playch_callback);
#endif

#endif

#ifdef DVR_PVR_SUPPORT
#ifndef _S3281_
	if(sys_ic_get_chip_id() != ALI_S3811) //S3811 has no tsg.
	{
	#ifdef SUPPORT_CAS_A
		tsg_init(0x5a); 
	#else
	    tsg_init(0x18); // 0x5a
#endif		
	}
#endif		
#endif

#ifdef SUPPORT_CAS9
    if(RET_SUCCESS!=verify_stbinfo_sig())
    {
    	hw_watchdog_reboot();
    	while(1);
    }
#endif

	ap_task_init();
	key_Init();
    
#if ((!defined _S3811_)&&(!defined _S3281_)&&(!defined _M3503_)&&(!defined _M3821_))
    PinMux_Conflict_Detect() ;  //for M36xx IC only
#endif

	PRINTF("APP init finished...\n");
#ifdef _PM_TEST_SUPPORT_
	process_monitor();
#endif
#if (defined SCPI_SUPPORT)
	scpi_Init();
#endif

	dog_init();
	return;
}

#ifdef _PM_TEST_SUPPORT_
void process_monitor(void)
{
	UINT32 i, j = 0x00000003;
	libc_printf("-->PM TEST Start:\n");
#ifdef _S3811_	
	for(i = 0; i<16; i++)
	{	
		UINT32 pm_finish = 0;
		UINT32 pm2_finish = 0;
		UINT32 pm3_finish = 0;
		UINT32 pm4_finish = 0;
		UINT32 pm5_finish = 0;
		*((volatile UINT32 *)0xb8000300) = (j|i<<16);
		while(1)
		{
			pm_finish = *((volatile UINT32 *)0xb8000304);
			pm2_finish = *((volatile UINT32 *)0xb8000310);
			pm3_finish = *((volatile UINT32 *)0xb8000314);
			pm4_finish = *((volatile UINT32 *)0xb8000318);
			pm5_finish = *((volatile UINT32 *)0xb800031c);
			if(1==(pm_finish&0x1)&&1==(pm2_finish&0x1)&&1==(pm3_finish&0x1)&&1==(pm4_finish&0x1)&&1==(pm5_finish&0x1))
				break;
			osal_task_sleep(1);
		}
		libc_printf("PM_COUNT:  \t=\t 0x%04x,  \tPM_SEL =  \t%d\n", pm_finish>>16, i);
		libc_printf("PM_COUNT2: \t=\t 0x%04x,  \tPM_SEL2 =  \t%d\n", pm2_finish>>16, i);
		libc_printf("PM_COUNT3:  \t=\t 0x%04x,  \tPM_SEL3 =  \t%d\n", pm3_finish>>16, i);
		libc_printf("PM_COUNT4: \t=\t 0x%04x,  \tPM_SEL4 =  \t%d\n", pm4_finish>>16, i);
		libc_printf("PM_COUNT5:  \t=\t 0x%04x,  \tPM_SEL5 =  \t%d\n", pm5_finish>>16, i);
		*((volatile UINT32 *)0xb8000300) = 0;
	}
#endif	
	libc_printf("PM Test Finished !!!\n");
}
#endif

